/**
 *
 *
 * @author TOTORO
 * @date 2021/6/25 15:59
 */

var $openSelectInput = jQuery;
$(function () {
    // 点击更多筛选条件，展示高级查询
    $(".search-mod__more-button___nbIba").click(function () {
        var $id = $(this).attr("id");
        if($id == "gd"){
            $(this).prop("id","jj");
            $(".more-part").hide();
            $(this).find("img").prop("src","//img.alicdn.com/tps/TB1jK1dIVXXXXXzXVXXXXXXXXXX.png");
        } else{
            $(this).prop("id","gd");
            $(".more-part").show();
            $(this).find("img").prop("src","//img.alicdn.com/tps/TB1HuWrIVXXXXcaXpXXXXXXXXXX.png");
        }
    });

    // 点击交易状态 打开交易状态选择面板  需要做判断，因为高级查询会影响其位置
    $(".small-select").click(function () {
        var isHas = $(this).hasClass("rc-select-open");
        if($(".search-mod__more-button___nbIba").attr("id") == "jj"){
            // top: 188px;
            $(".rc-small-select").css("top",188);
        } else{
            // top :320px
            $(".rc-small-select").css("top",320);
        }
        if(isHas){
            $(this).removeClass("rc-select-open");
            $(".rc-small-select").slideUp(100);
        } else{
            $(this).addClass("rc-select-open");
            $(".rc-small-select").slideDown(100);
        }
    });

    // 点击高级查询中的下拉框选择，展示对应的下拉框出来
    $(".rc-select").click(function () {
        $openSelectInput = $(this);
        var isHas = $(this).hasClass("rc-select-open");
        var $nowSelect = $(".select-"+$(this).attr("data-select-class"));
        if($nowSelect.css("display") == 'none'){
            var $x = $(this).offset().left;
            var $y = $(this).offset().top;
            // 获取当前下拉框的高度和宽度
            var $width = $(this).width();
            var $height = $(this).height();
            $nowSelect.css({"top":(parseInt($y)+32)+"px","left":$x+"px"});
            if(isHas){
                $(this).removeClass("rc-select-open");
                $nowSelect.attr("")
                $nowSelect.slideUp(100);
            } else{
                $(this).addClass("rc-select-open");
                $nowSelect.slideDown(100);
            }
        }
    });

    // 点击/悬浮下拉框中的值
    $(".rc-select-dropdown-menu").find("li").hover(function () {
        $(this).addClass("rc-select-dropdown-menu-item-active");
    }, function () {
        $(this).removeClass("rc-select-dropdown-menu-item-active");
    }).click(function () {
        $openSelectInput.find(".rc-text").text($(this).text()).attr("data-value", $(this).attr(("data-value")));
        $(this).addClass("rc-select-dropdown-menu-item-selected").siblings().removeClass("rc-select-dropdown-menu-item-selected");
        $(this).removeClass("rc-select-open");
        $(".select-"+$openSelectInput.attr("data-select-class")).slideUp(100);
    });

    //点击其他文档下拉框消失
    $(document).mouseup(function(e) {
        var con = $('.rc-select-dropdown');
        e.stopPropagation();
        if (con.has(e.target).length == 0) {
            $('.rc-select-dropdown').slideUp(100);
            $(".rc-select-enabled").removeClass("rc-select-open");
        }
    });

    // 表格上的选择面板悬浮效果 / 点击效果
    $(".rc-small-select").find("li").hover(function () {
        $(this).addClass("rc-select-dropdown-menu-item-active");
    }, function () {
        $(this).removeClass("rc-select-dropdown-menu-item-active");
    }).click(function () {
        $("#status").text($(this).text());
        $(this).addClass("rc-select-dropdown-menu-item-selected").siblings().removeClass("rc-select-dropdown-menu-item-selected");
        $(".rc-select").removeClass("rc-select-open");
        $(".rc-select-dropdown").slideUp(100);
    });

    // 点击不同类型的订单
    $("#allOrder").click(function () {
        $(".loading-mod__loading___3nGTY").show();
        setTimeout(function () {
            window.location.href = "/user/boughtBaby.htm";
        },700);
    });
    $("#waitPay").click(function () {
        $(".loading-mod__loading___3nGTY").show();
        setTimeout(function () {
            window.location.href = "/user/boughtBaby.htm?tabCode=waitPay";
        },500);

    });
    $("#waitSend").click(function () {
        $(".loading-mod__loading___3nGTY").show();
        setTimeout(function () {
            window.location.href = "/user/boughtBaby.htm?tabCode=waitSend";
        },500);

    });
    $("#waitConfirm").click(function () {
        $(".loading-mod__loading___3nGTY").show();
        setTimeout(function () {
            window.location.href = "/user/boughtBaby.htm?tabCode=waitConfirm";
        },500);

    })
    $("#waitRate").click(function () {
        $(".loading-mod__loading___3nGTY").show();
        setTimeout(function () {
            window.location.href = "/user/boughtBaby.htm?tabCode=waitRate";
        },500);

    });

    // 点击订单普通搜索
    $("#orderSearch").click(function () {
        var productTitleOrOrderId = $("#orderOrTitle").val();
        var tabCode = Totoro.getQueryVariable("tabCode");
        window.location.href = "/user/boughtBaby.htm?tabCode="+tabCode+"&productTitleOrOrderId="+productTitleOrOrderId;
    })

    // 点击更多筛选搜索
    $("#searchTrem").click(function () {
        // 收集所有的条件
        var evaStatus = $(".eva-val").attr("data-value");
        var transactionStatus = $(".transaction-val").attr("data-value");
        var sellerName = $("#sellerName").val();
        var startTime = $("#startTime").val();
        var endTime = $("#endTime").val();

        var evaUrl = Totoro.changeURLPar(window.location.href, "evaStatus", evaStatus);
        var startTimeUrl = Totoro.changeURLPar(evaUrl, "startTime", startTime);
        var endTimeUrl = Totoro.changeURLPar(startTimeUrl, "endTime", endTime);
        var sellerNameUrl = Totoro.changeURLPar(endTimeUrl, "sellerName", sellerName);
        var finalUrl = Totoro.changeURLPar(sellerNameUrl, "transactionStatus", transactionStatus);
        window.history.pushState(null,null,finalUrl);//向当前url添加参数
        window.location.reload();
    });

    // 全选
    $(".allChecked").click(function () {
        var _this = $(this);
        $(".allChecked").each(function () {
            $(this).prop("checked", _this.prop("checked"));
        });
        $(".scopeChecked").each(function () {
            if(!$(this).prop("disabled")) {
                $(this).prop("checked", _this.prop("checked"));
            }
        })
    });

    // 点击商品上的复选框，如果都选完了，则点亮全选
    $(".scopeChecked").click(function () {
        var notCkLength = $(".scopeChecked").not("input:checked").length;
        if(notCkLength < 1){
            $(".allChecked").each(function () {
                $(this).prop("checked", true);
            });
        } else{
            $(".allChecked").each(function () {
                $(this).prop("checked", false);
            });
        }
    })

    // 批量确认收货
    $(".batchReceipt").click(function () {
        // 获取是否有选中的
        var isHaveChecked = $(".scopeChecked:checked").length<1?false:true;
        if(!isHaveChecked){
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.open({
                    title: '已买到的宝贝'
                    ,content: '你还未选择需要收货的宝贝'
                    ,offset: '300px'
                });
            });
            return false;
        }
        // 拿到所有需要批量收货的订单号
        var bizOrderIds = new Array();
        $(".scopeChecked:checked").each(function () {
            var odd = $(this).parents(".js-order-container").attr("data-odd");
            bizOrderIds.push(odd);
        });
        // 要求用户输入你的支付密码
        layer.prompt({
            title: '请输入你的支付密码',
            formType: 1,
            offset: '300px',
            maxlength: 6
            },
            function(value, index, elem){
            $.ajaxSettings.async = false;
                $.post("/order_logic/quitePayPassword.htm", {"payPassword": value}, (res =>{
                    if(res == 'fail'){
                        layer.msg('支付密码错误！', {icon: 2, time: 1500, offset: '300px'});
                    } else{
                        layer.msg('支付密码成功，正在为您自动批量收货！', {icon: 1, time: 1500, offset: '300px'});
                        // 如果比对成功正确
                        setTimeout(v=>{
                            $.post("/order_logic/batch_confirm_goods.htm", {"bizOrderIds": bizOrderIds}, function (res) {
                                if(res == "success"){
                                    window.location.reload();
                                }
                            })
                        }, 400);
                    }
                }));
                setTimeout( v=>{
                    layer.close(index);
                }, 1500);
            });
    })


    // 日期
    layui.use('laydate', function() {
        var laydate = layui.laydate;
        //日期范围
        laydate.render({
            elem: '#test6'
            //设置开始日期、日期日期的 input 选择器
            //数组格式为 2.6.6 开始新增，之前版本直接配置 true 或任意分割字符即可
            ,range: ['#startTime', '#endTime']
        });
    });

    // 取消订单
    $("#cancelOrder").click(function () {
        var _this = $(this);
        layui.use('layer', function() {
            var layer = layui.layer;
            layer.confirm('您还未付款，确定取消该订单?',{offset: '300px', title: '已买到的宝贝'}, function (index) {
                var odd = _this.parents(".js-order-container").attr("data-odd");
                $.post("/order_logic/updateOrderStatus.htm", {"bizOrderId": odd, "status":8}, function () {
                    layer.msg("订单已关闭！", {offset: '300px'});
                    _this.parents(".bought-wrapper-mod__trade-order___2lrzV").addClass("bought-wrapper-mod__closed___3pIh6");
                    _this.parent().parent().remove();
                })
                layer.close(index);
            });
        });
    });

    // 删除订单
    $(".delete-order").click(function () {
        var moId = $(this).parents(".js-order-container").attr("data-mo-id");
        var _this = $(this);
        generateDeleteTips().appendTo($("body"));
        // 确定删除
        $(".ok-delete").off("click").on("click",function(){
            $.post("/order_logic/falseDeleteOrder.htm", {"moId": moId}, (res)=>{

            });
            $("#deleteDialog").remove();
            $(".loading-mod__loading___3nGTY").show();
            setTimeout(res=> {
                $(".loading-mod__loading___3nGTY").hide();
                // 删除html元素
                _this.parents(".js-order-container").remove();
                emptyStatus();
            }, 500);
        })
    });

    // 关闭删除订单弹出框
    $("body").on("click", ".not-delete", function () {
        $("#deleteDialog").remove();
    });

    // 确定删除
    $("body").on("click", ".ok-delete", function () {
        $("#deleteDialog").remove();
        $(".loading-mod__loading___3nGTY").show();
        setTimeout(res=> {
            $(".loading-mod__loading___3nGTY").hide();
            // 删除html元素
            $(this).parents(".js-order-container").remove();
        }, 500);
    })


    // 上方分页按钮控制分页
    $("#prevCurr").click(function () {
        var curr = parseInt(Totoro.getQueryVariable("nowPage"))-1;
        var newUrl = Totoro.changeURLPar(window.location.href, "nowPage", curr);
        window.location.href = newUrl;
    });
    $("#nextCurr").click(function () {
        var curr = parseInt(Totoro.getQueryVariable("nowPage"))+1;
        var newUrl = Totoro.changeURLPar(window.location.href, "nowPage", curr);
        window.location.href = newUrl;
    })


    //  分页
    layui.use(['laypage', 'layer'], function() {
        var laypage = layui.laypage
            , layer = layui.layer;
        //完整功能
        laypage.render({
            elem: 'tmallPagination'
            , count: $("#allPage").val()
            , theme: '#f40'
            , limit: 10
            , layout: ['count', 'prev', 'page', 'next', 'skip']
            , curr: Totoro.getQueryVariable("nowPage")
            , jump: function(obj, first){
                //首次不执行
                if(!first){
                    var tabCode = Totoro.getQueryVariable("tabCode");
                    window.location.href = "/user/boughtBaby.htm?tabCode="+tabCode+"&nowPage="+obj.curr;
                }
            }
        });
    });
});

var generateDeleteTips = function(){
    return $("<div class='tm-dialog-container' id='deleteDialog'>\n" +
        "    <div class='tm-dialog-wrap'>\n" +
        "        <div class='tm-dialog-mask'>\n" +
        "        </div>\n" +
        "        <div class='tm-dialog ' style='left: 756px; top: 250px;'>\n" +
        "            <div class='tm-dialog-content'>\n" +
        "                <div class='tm-dialog-body'>\n" +
        "                    <div class='confirm-mod__container___3XPq5'>\n" +
        "                        <div class='confirm-mod__header___14yoA'>您确定要删除该订单吗？</div>\n" +
        "                        <div class='confirm-mod__body___1J3we'>\n" +
        "                            <span>删除后，您可在订单回收站找回，或永久删除。</span>\n" +
        "                            <div class='confirm-mod__inputs-container___3ozMb'></div>\n" +
        "                        </div>\n" +
        "                        <div class='confirm-mod__footer___1e5Qm'>\n" +
        "                            <button\n" +
        "                                class='button-mod__button___2Ew0a button-mod__secondary___RRGMH confirm-mod__button___ZUjXz ok-delete'>确定\n" +
        "                                </button>\n" +
        "                                    <button\n" +
        "                                        class='button-mod__button___2Ew0a button-mod__grey___3CiQ2 confirm-mod__button___ZUjXz not-delete'>关闭\n" +
        "                                        </button>\n" +
        "                        </div>\n" +
        "                    </div>\n" +
        "                </div>\n" +
        "            </div>\n" +
        "            <div tabIndex='0' style='width:0;height:0;overflow:hidden;'>sentinel\n" +
        "            </div>\n" +
        "        </div>\n" +
        "    </div>\n" +
        "</div>");
}

// 所有订单都删除了或者还原了，则设置页面数据为空状态
var emptyStatus = function () {
    // 获得所有订单，判断长度
    var orderCount = $(".js-order-container").length;
    if(orderCount < 1){
        $(".operating").remove();
        $(".js-empty-list").show();
    }
}
